package com.study.rabbit.simpledemo;

import java.text.SimpleDateFormat;
import java.util.Date;
import org.junit.Test;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.QueueingConsumer.Delivery;

public class SimpleDemo {

	private static final String QUEUE_NAME = "testQueue";
	private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssss");

	@Test
	public void testRabbitMQMsgPull() {
		try {
			ConnectionFactory factory = new ConnectionFactory();
			factory.setHost("localhost");
			factory.setUsername("admin");
			factory.setPassword("admin");
			//factory.setPort(5672);
			Connection connection = factory.newConnection();

			Channel channel = connection.createChannel();
			int count = 10;
			while (true) {
				channel.queueDeclare(QUEUE_NAME, false, false, false, null);
				String message = "Hello World!--->" + sdf.format(new Date());
				Thread.sleep(1000);
				channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
				System.out.println(" send message '" + message + "' success!");
				count--;
				if (count < 0)
					return;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Test
	public void testRabbitMQMsgPush() {
		try {
			ConnectionFactory factory = new ConnectionFactory() ;  
			factory.setHost("localhost");
			factory.setUsername("admin");
			factory.setPassword("admin");
			//factory.setPort(5672);
	        System.out.println("#####"+factory.getPort());
	        Connection conn = factory.newConnection() ;  
	        Channel channel = conn.createChannel() ;  
	        channel.queueDeclare(QUEUE_NAME, false, false, false, null) ;  
	        //上面的部分，与Sender01是一样的  
	        //配置好获取消息的方式  
	        QueueingConsumer consumer = new QueueingConsumer(channel) ;  
	        channel.basicConsume(QUEUE_NAME, true, consumer) ;  
	        //循环获取消息  
	        while(true){
	            //获取消息，如果没有消息，这一步将会一直阻塞  
	            Delivery delivery = consumer.nextDelivery() ;  
	            String msg = new String(delivery.getBody()) ;    
	            System.out.println("received message[" + msg + "] from " + QUEUE_NAME);  
	        }
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
